import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import {Modal, Button, InputNumber, message, Form, Radio, Space, Tooltip, Typography, Input, Select, Card, Row, Col} from 'antd';
import styles from '../../../components/common/PateoTable/TableList.less';
import { FormInstance } from 'antd/lib/form';
import { transferOption } from "@/utils/common";


const TextArea = Input.TextArea;
const mapStateToProps = (state: any) => ({
  monitorAlarmSetting: state.monitorAlarmSetting,
//   user: state?.menu?.userProfile
});
class SettingModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    this.state = {
      buttonLoading: false,
      defaultValues: {
        brandId: '',
        brandName: '',
        seriesId: '',
        seriesName: '',
        wakeupCounterThreshold: undefined,
        warningRule: '',
        warningFreq: '',
        maxWarningCount: 1
      },
      vehicleSeriesData: []
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, user, data, dispatch, type = 'add' } = this.props
    const { defaultValues } = this.state
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      const formData = type === 'add' ? Object.assign({}, defaultValues) : Object.assign({}, data)
      /* this.setState({
        currentCase: formData.userCase
      }) */
      this.setState({ vehicleSeriesData: [] });
      this.formRef.current?.setFieldsValue({
        ...formData,
        // operator: user?.accountName
      })
      if (type === 'edit') {
        this.getVehicleSeriesData()
      }
    }
  }

  //  获取品牌下车系数据
  getVehicleSeriesData = () => {
    const brandId = this.formRef.current && this.formRef.current.getFieldValue('brandId');
    /* this.formRef.current && this.formRef.current.setFieldsValue({
      seriesId: '',
    }) */
    brandId && this.props.dispatch({
      type: 'vehicleInfoQuery/getDataWithRes',
      payload: {
        url: '/common/vehicle/getserieslist',
        brandId,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({ vehicleSeriesData: res.data });
        }
      }
    })
  }

  close = () => {
    const { closeModal } = this.props;
    closeModal();
    this.formRef.current?.resetFields();
    this.setState({
      buttonLoading: false,
    });
  };

  ok = (values: any) => {
    const { dispatch, type = 'add', refresPage } = this.props;
    this.setLoading(true);
    const url = type === 'add' ? '/can/op/network/warningconfig/add' : '/can/op/network/warningconfig/edit';
    dispatch({
      type: 'monitorAlarmSetting/postObjWithRes',
      payload: {
        url,
        ...values
      },
      callback: (res: any) => {
        this.setLoading(false);
        if (res.statusCode === '0') {
          message.success('保存成功');
          this.close();
          refresPage();
        } else {
          message.error(res.statusMessage);
        }
      }
    })
  }

  setLoading = (flag: any) => {
    this.setState({
      buttonLoading: flag,
    });
  };

  handleEnsure = () => {
    //  确定按钮
    this.formRef.current?.submit();
  }

  render() {
    const { modalVisible, extraData: { brandList = [] }, type = 'add' } = this.props;
    const prefix = type && type === 'edit' ? '修改' : '新增';
    const { vehicleSeriesData, buttonLoading } = this.state;

    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" onClick={this.handleEnsure} type="primary">
          提交
        </Button>
        {/* <Button size="small" loading={loading} onClick={this.handleLock} type="primary">
          保存
        </Button> */}
      </div>
    );

    return (
      <Modal
        title={`${prefix}报警配置`}
        // style={{ width: '800px' }}
        width={800}
        // bodyStyle={{ maxHeight: '700px' }}
        okButtonProps={{ loading: buttonLoading }}
        footer={footer}
        visible={modalVisible}
        onCancel={this.close}
      >
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          style={{ marginTop: 12 }}
          ref={this.formRef}
          onFinish={this.ok}
          // layout="vertical"
        >
          <Row gutter={16}>
            {/* <Col lg={12} md={12} sm={12}>
              <Form.Item
                label="车系"
                name="seriesId"
                rules={[{ required: false, message: '车系' }]}
              >
                <Select placeholder="请选择车系">
                  { transferOption(vehicleSeriesData, ["value","label"])}
                </Select>
              </Form.Item>
            </Col> */}
            <Col lg={12} md={12} sm={12}>
              { type === 'edit' ? (
                <Form.Item name="sid" noStyle>
                  <Input type="hidden" />
                </Form.Item>
              ) : null }
              <Form.Item name="brandName" noStyle>
                <Input type="hidden" />
              </Form.Item>
              {/* {type === 'edit' ? () : null } */}
              <Form.Item
                label="品牌"
                name="brandId"
                rules={[{ required: true, message: '请选择品牌' }]}
              >
                <Select 
                  labelInValue
                  placeholder="请选择品牌"
                  disabled={ type === 'edit' }
                  onChange={(value: { value: string; label: React.ReactNode }) => {
                    this.formRef.current && this.formRef.current.setFieldsValue({
                      seriesId: '',
                      seriesName: '',
                      brandId: value.value,
                      brandName: value.label,
                    })
                    this.setState({ vehicleSeriesData: [] })
                    this.getVehicleSeriesData()
                  }}
                >
                  { transferOption(brandList, ["brandCode","brandName"])}
                </Select>
              </Form.Item>
            </Col>
            <Col lg={12} md={12} sm={12}>
              <Form.Item
                label="报警规则"
                name="warningRule"
                rules={[{ required: true, message: '请选择报警规则' }]}
              >
                <Select placeholder="请选择报警规则" options={[
                  {
                    value: 1,
                    label: '达到阈值时',
                  },
                  {
                    value: 2,
                    label: '达到阈值倍数时',
                  }
                ]}></Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            {/* <Col lg={12} md={12} sm={12}>
              <Form.Item
                label="监控项"
                name="point"
              >
                <Select placeholder="请选择监控项" options={[
                  {
                    value: '0',
                    label: '整车网络异常计数',
                  },
                  {
                    value: '1',
                    label: '唤醒计数',
                  }
                ]}></Select>
              </Form.Item>
            </Col> */}
            <Col lg={12} md={12} sm={12}>
              <Form.Item name="seriesName" noStyle>
                <Input type="hidden" />
              </Form.Item>
              <Form.Item
                label="车系"
                name="seriesId"
                rules={[{ required: true, message: '请选择车系' }]}
              >
                <Select 
                  labelInValue
                  placeholder="请选择车系"
                  disabled={ type === 'edit' }
                  onChange={(value: { value: string; label: React.ReactNode }) => {
                    this.formRef.current && this.formRef.current.setFieldsValue({
                      seriesId: value.value,
                      seriesName: value.label,
                    })
                  }}
                >
                  { transferOption(vehicleSeriesData, ["code","name"])}
                </Select>
              </Form.Item>
            </Col>
            <Col lg={12} md={12} sm={12}>
              <Form.Item
                label="报警频率"
                name="warningFreq"
                rules={[{ required: true, message: '请选择报警频率' }]}
              >
                <Select placeholder="请选择报警频率" options={[
                  {
                    value: 1,
                    label: '每天',
                  },
                  {
                    value: 2,
                    label: '每周',
                  },
                  {
                    value: 3,
                    label: '每月',
                  }
                ]}></Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={12}>
              <Form.Item
                label="唤醒计数报警阈值"
                labelCol={{span: 9}}
                wrapperCol={{span: 13}}
                name="wakeupCounterThreshold"
                rules={[{ required: true, message: '请输入唤醒计数报警阈值' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  max={255}
                  min={1}
                  placeholder="请输入报警阈值" />
              </Form.Item>
            </Col>
            <Col lg={12} md={12} sm={12}>
              <Form.Item
                label="最大报警次数"
                name="maxWarningCount"
                labelCol={{span: 7}}
                wrapperCol={{span: 15}}
                rules={[{ required: true, message: '请输入最大报警次数' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  max={100}
                  min={1}
                  placeholder="请输入报警次数" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(SettingModal);
